package com.summer.safe.controller;

import com.summer.safe.base.BaseController;
import com.summer.safe.base.Page;
import com.summer.safe.config.properties.ConfigureProperties;
import com.summer.safe.config.result.ResultCode;
import com.summer.safe.config.annotation.ResultWrapper;
import com.summer.safe.entity.GenScheme;
import com.summer.safe.entity.GenTable;
import com.summer.safe.entity.GenTableColumn;
import com.summer.safe.exception.CustomException;
import com.summer.safe.service.GenSchemeService;
import com.summer.safe.service.GenTableService;
import com.summer.safe.utils.StringUtils;
import com.summer.safe.utils.ToolUtil;
import com.summer.safe.utils.GenUtils;
import com.summer.safe.utils.GenerateConfig;
import com.summer.safe.utils.SimpleTemplateEngine;
import com.summer.safe.utils.TemplateEngine;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 生成方案Controller
 *
 */
@Controller
@RequestMapping(value = "/gen/genScheme")
public class GenSchemeController extends BaseController {

    @Autowired
    private GenSchemeService schemeService;


    @Autowired
    private GenTableService tableService;

    @Resource
    private ConfigureProperties configureProperties;

    @ModelAttribute("genScheme")
    public GenScheme get(@RequestParam(required=false) String id) {
        if (StringUtils.isNotBlank(id)){
            return schemeService.get(id);
        }else{
            return new GenScheme();
        }
    }

    @RequiresPermissions("gen:genScheme:view")
    @RequestMapping("")
    public String index(Model model) {
        model.addAttribute("table", getTable());
        return "schemelist.html";
    }

    @RequestMapping("/dataList")
    @ResultWrapper
    public Page<GenScheme> list(GenScheme genScheme, HttpServletRequest request) {
        Page<GenScheme> page = schemeService.findPage(new Page(request), genScheme);
        return page;
    }

    @PostMapping("/add")
    public String add(Model model) {
        model.addAttribute("table", getTable());
        model.addAttribute("genScheme", new GenScheme());
        return "add.html";
    }

    @RequiresPermissions("gen:genScheme:edit")
    @GetMapping("/form")
    public String form(GenScheme genScheme, Model model) {
        genScheme = schemeService.get(genScheme);
        if (genScheme == null) {
            genScheme = new GenScheme();
            genScheme.setPackageName(configureProperties.getPackageName());
        }
        model.addAttribute("table", getTable());
        model.addAttribute("genScheme", genScheme);
        return "schemeform.html";
    }
    /**
     * 根据表名称获得业务表信息
     */
    @GetMapping("/getGenScheme")
    @ResultWrapper(ResultCode.SUCCESS_QUERY)
    public GenScheme getGenTableByName( String tableName){
        GenScheme genScheme=schemeService.getGenScheme(tableName);

        if (genScheme == null) {
            genScheme = new GenScheme();
            genScheme.setPackageName(ToolUtil.getPackageName());
        }

        return genScheme;
    }
    /**
     * 获得数据库中的表
     */
    private Map<String, String> getTable(){
        Map<String, String> map = new HashMap<>(16);
        tableService.findList(new GenTable()).forEach(g ->
                map.put(g.getId(), g.getName() + ":" + g.getComments())
        );
        return map;
    }

    /**
     * 保存并生成
     * @param genScheme
     */
    @PostMapping(value = "save")
    @ResultWrapper(ResultCode.GENERATE_SAVE)
    public void save(GenScheme genScheme) {

        genScheme.setGenTable(tableService.getGenTableByName(genScheme.getGenTable()));
        schemeService.save(genScheme);
        try {
            //获取生成表数据
            GenTable table = tableService.get(genScheme.getGenTable());
            //获取生成表列数据
            GenTableColumn tableColumn = new GenTableColumn();
            tableColumn.setGenTable(table);
            List<GenTableColumn> tableColumnList = tableService.findTableColumnList(tableColumn);

            GenerateConfig config = GenUtils.config(table, genScheme, tableColumnList);

            TemplateEngine templateEngine = new SimpleTemplateEngine(config);
            templateEngine.start();
        }catch ( Exception e){
            logger.error("抛出的异常{}", e.getMessage());
            throw new CustomException("1",e.getMessage());
        }

    }

    /**
     * 删除
     * @param genScheme
     */
    @RequestMapping(value = "delete")
    @ResultWrapper(ResultCode.SUCCESS_DELETE)
    public void delete(GenScheme genScheme) {
        schemeService.delete(genScheme);
    }

}
